package com.xzs.jersey.util;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSocketFactory;
import javax.net.ssl.TrustManager;
import java.io.*;
import java.net.ConnectException;
import java.net.URL;

/**
 *
 */

public class HttpUtil {


    /**
     * 发起https请求并获取结果
     *
     * @param requestUrl    请求地址
     * @param requestMethod 请求方式（GET、POST） 必须大写
     * @param outputStr     提交的数据
     * @return JSONObject(通过JSONObject.get ( key)的方式获取json对象的属性值)
     */
    public static JSONObject httpsRequest(String requestUrl, String requestMethod, String outputStr) {

        JSONObject jsonObject = null;
        StringBuffer buffer = new StringBuffer();
        InputStream inputStream = null;
        InputStreamReader inputStreamReader = null;
        BufferedReader bufferedReader = null;
        HttpsURLConnection httpUrlConn = null;
        try {
            // 创建SSLContext对象，并使用我们指定的信任管理器初始化
            TrustManager[] tm = {new MyX509TrustManager()};
            SSLContext sslContext = SSLContext.getInstance("SSL", "SunJSSE");
            sslContext.init(null, tm, new java.security.SecureRandom());
            // 从上述SSLContext对象中得到SSLSocketFactory对象
            SSLSocketFactory ssf = sslContext.getSocketFactory();

            URL url = new URL(requestUrl);
            httpUrlConn = (HttpsURLConnection) url.openConnection();
            httpUrlConn.setSSLSocketFactory(ssf);

            httpUrlConn.setDoOutput(true);
            httpUrlConn.setDoInput(true);
            httpUrlConn.setUseCaches(false);
            // 设置请求方式（GET/POST）
            httpUrlConn.setRequestMethod(requestMethod);

            if ("GET".equalsIgnoreCase(requestMethod)) {
                httpUrlConn.connect();
            }

            // 当有数据需要提交时
            if (null != outputStr) {
                OutputStream outputStream = httpUrlConn.getOutputStream();
                // 注意编码格式，防止中文乱码
                outputStream.write(outputStr.getBytes("UTF-8"));
                outputStream.close();
            }

            // 将返回的输入流转换成字符串
            inputStream = httpUrlConn.getInputStream();
            inputStreamReader = new InputStreamReader(inputStream, "utf-8");
            bufferedReader = new BufferedReader(inputStreamReader);

            String str = null;
            while ((str = bufferedReader.readLine()) != null) {
                buffer.append(str);
            }
            jsonObject = JSONObject.fromObject(buffer.toString());
        } catch (ConnectException ce) {
            System.out.println("server connection timed out.");
        } catch (Exception e) {
            System.out.println("https request error:");
        } finally {
            try {
                if (bufferedReader != null) {
                    bufferedReader.close();
                }
                if (inputStreamReader != null) {
                    inputStreamReader.close();
                }
                if (inputStream != null) {
                    inputStream.close();
                }
                httpUrlConn.disconnect();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return jsonObject;
    }

    public static void main(String[] args) {
        String id = "2941314652";
        String musicListURL = "https://api.imjad.cn/cloudmusic/?type=playlist&id=${id}";
        musicListURL = musicListURL.replace("${id}", id);

        JSONObject musics = HttpUtil.httpsRequest(musicListURL, "GET", null);
        JSONObject musicList = (JSONObject) musics.get("playlist");
        JSONArray ids = musicList.getJSONArray("tracks");
//        JSONArray ids = musicList.getJSONArray("trackIds");
        int i = 0;
        for (; i < ids.size(); i++) {
            JSONObject music = ids.getJSONObject(i);
            String name = music.getString("name");
//            String name = String.valueOf(i);
            String musicId = music.getString("id");
            String getDownURl = "https://api.imjad.cn/cloudmusic/?type=song&id=${musicID}&br=320000";
            getDownURl = getDownURl.replace("${musicID}", musicId);
            JSONObject musicsDownUrls = HttpUtil.httpsRequest(getDownURl, "GET", null);
            JSONArray urls = musicsDownUrls.getJSONArray("data");
            String musicsDownUrl = urls.getJSONObject(0).getString("url");

            HttpsURLConnection httpUrlConn = null;
            InputStream inputStream = null;
            FileOutputStream fos = null;
            try {
                URL url = new URL(musicsDownUrl);
                httpUrlConn = (HttpsURLConnection) url.openConnection();
                httpUrlConn.setDoOutput(true);
                httpUrlConn.setDoInput(true);
                httpUrlConn.setUseCaches(false);
                // 设置请求方式（GET/POST）
                httpUrlConn.setRequestMethod("GET");
                // 将返回的输入流转换成字符串
                inputStream = httpUrlConn.getInputStream();
                File file = new File("/Users/xuzs/Desktop/music/" + name + ".mp3");
                fos = new FileOutputStream(file);
                byte[] b = new byte[1024];
                int nRead = 0;
                while ((nRead = inputStream.read(b)) != -1) {
                    fos.write(b, 0, nRead);
                }
                fos.flush();
            } catch (IOException ioe) {
                ioe.printStackTrace();
            } finally {
                try {
                    if (fos != null) {
                        fos.close();
                    }
                    if (inputStream != null) {

                        inputStream.close();
                    }
                    httpUrlConn.disconnect();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        System.out.println(i);
    }

}
